package com.jhj.provider.resume.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;
import com.jhj.provider.resume.po.b.model.Resume;
import com.jhj.provider.resume.po.b.model.ResumeShare;
import com.jhj.provider.resume.service.ResumeService;
import com.jhj.provider.resume.service.ResumeShareService;
import com.jhj.provider.resume.utils.Constants;
import com.jhj.utils.AppResultData;
import com.jhj.utils.HttpClientUtil;
import com.jhj.utils.ImgServerUtil;
import com.jhj.utils.JsonUtil;
import com.jhj.utils.TimeStampUtil;
import com.jhj.wx.utils.WxUtil;

@RestController
public class ResumeQrCodeController {


	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	ResumeService resumeService;
	
	@Autowired
	ResumeShareService resumeShareService;
	
	@Value("${img.host}")
	private String imgHost;
	
	/**
	 * @param resumeNo
	 * @param saleId
	 * @param saleMobile
	 * @return result
	 * 
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/api/resume/gen_resume_qrcode", method = RequestMethod.GET)
	public AppResultData<Object> getOrderContract(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "resumeNo") String resumeNo,
			@RequestParam(value = "saleId", required = false, defaultValue = "") Integer saleId,
			@RequestParam(value = "saleMobile", required = false, defaultValue = "") String saleMobile) {
		
		AppResultData<Object> result = new AppResultData<Object>(Constants.SUCCESS_0, "ok", "");
		Resume searchVo = new Resume();
		searchVo.setResumeNo(resumeNo);
		
		Resume resume = resumeService.selectOne(searchVo);
		if (resume == null) {
			return result;
		}
		
		Integer resumeId = resume.getResumeId();
		
		RestTemplate rest = new RestTemplate();
		String accessToken = WxUtil.getAccessToken(Constants.MP_USER_APP_ID, Constants.MP_USER_APP_SECERT);
		
		/**
		 * scene格式为
		 * [resumeId]-[saleId]-[saleMobile]
		 */
		String scene = resumeId + "-" + saleId + "-" + saleMobile;
				
		try {
			String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
			Map<String, Object> param = new HashMap<>();
			param.put("scene", scene);
			param.put("page", "pages/resume/detail/detail");
			Map<String,Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            logger.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
//            logger.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
            byte[] content = entity.getBody();

            //上传到图片服务器
            String imgUploadUrl = imgHost + "/upload/";
            
			String sendResult = ImgServerUtil.sendPostBytes(imgUploadUrl, content, "png");

            
			ObjectMapper mapper = new ObjectMapper();
			HashMap<String, Object> o = mapper.readValue(sendResult, HashMap.class);
			// String ret = o.get("ret").toString();
			HashMap<String, String> info = (HashMap<String, String>) o.get("info");
			String imgUrl = imgHost + "/" + info.get("md5").toString();
			
			if (!StringUtil.isEmpty(url)) {
				result.setData(imgUrl);
				
				//插入resume_share表
				ResumeShare resumeShareSearchVo = new ResumeShare();
				resumeShareSearchVo.setResumeNo(resumeNo);
				resumeShareSearchVo.setSaleId(saleId);
				ResumeShare resumeShare = resumeShareService.selectOne(resumeShareSearchVo);
				if (resumeShare != null) {
					resumeShare.setQrcode(imgUrl);
					resumeShareService.update(resumeShare);
				}
			}
			
			//更新resume为发布状态
			resume.setPublish(1);
			resume.setUpdateTime(TimeStampUtil.getNowSecond().intValue());
			resumeService.update(resume);
			
		} catch (Exception e) {
			logger.error("调用小程序生成微信永久小程序码URL接口异常", e);
		} finally {
			
		}
		return result;
	}
}
